from tinydb import TinyDB, Query, where


class Tiny_setting:
    tinydb = TinyDB('setting.json')  # 加载JSON文件

    def insert_data(self, tb_name, kv_dic):  # 将KV_DIC字典插入到表名TB_NAME中
        table = self.tinydb.table(tb_name)
        table.insert(kv_dic)

    def del_data(self, tb_name, condition):  # 将TB_NAME中符合CONDITION条件的删除，使用方法如注释
        table = self.tinydb.table(tb_name)
        table.remove(condition)
        # condition = Query()
        # del_data('table_b', condition.age == 16)

    def update_data(self, tb_name, new_dic, key=None, value=None):  # 将TB_NAME中符合KEY=VALUE的值更新为NEW_DIC
        print(tb_name, new_dic, key, value)
        table = self.tinydb.table(tb_name)
        if key:
            table.update(new_dic, where(key) == value)
        else:
            table.update(new_dic)

    def search_data(self, tb_name, condition):  # 查找TB_NAME中符合CONDITION的结果，使用方法如注释
        table = self.tinydb.table(tb_name)
        data = table.search(condition)
        return data
        # qry = Query()
        # data = search_data('table_b', qry.name=='andy')

    def all_data(self, tb_name):  # 查找TB_NAME中所有的结果
        table = self.tinydb.table(tb_name)
        data = table.all()
        return data